import argparse
import json
import os.path
import re
import traceback

import pytest

BASE_DIR = os.path.dirname(__file__)

parser = argparse.ArgumentParser(description='manual to this scription')
parser.add_argument('--test_num', type=str, default='1/1')
parser.add_argument('--save_path', type=str, default='./report')
parser.add_argument('--device_num', type=str, default='')
args = parser.parse_args()

run_params = ['-vs']

try:
    sn = args.device_num
    run_params.extend(['--sn={}'.format(sn)])

    # 报告保存路径
    report = os.path.join(args.save_path, '{}_report.html'.format(sn))
    run_params.extend(['--html={}'.format(report), '--self-contained-html', '--capture=sys'])

    with open(os.path.join(BASE_DIR, 'testcases.json'), 'r', encoding='utf-8') as f:
        test_cases_list = [case.get('case_file') for case in json.load(f)]
    test_num = args.test_num
    if test_num == '1/2':
        selected_case = test_cases_list[:len(test_cases_list) // 2]
    elif test_num == '2/2':
        selected_case = test_cases_list[len(test_cases_list) // 2:]
    else:
        selected_case = test_cases_list

    print(run_params)
    pytest.main(run_params + ['--cache-clear'] + selected_case)
    print('获取测试结果')

    with open(report, 'r+', encoding='gbk') as f:
        text = f.read()
        text = text.replace('<meta charset="utf-8"/>', '<meta charset="gbk"/>')
        f.seek(0)
        f.write(text)
    # 失败重跑
    cur_dir = os.path.dirname(__file__)
    cache_dir = os.path.join(cur_dir, '.pytest_cache', 'v', 'cache', 'lastfailed')
    if os.path.exists(cache_dir):
        failed_case = list(json.load(open(cache_dir, 'r', encoding='utf-8')).keys())
        if failed_case:
            print('rerun last failed case')
            rerun_report = os.path.join(args.save_path, '{}_rerun_report.html'.format(sn))
            run_params[2] = '--html={}'.format(rerun_report)
            pytest.main(run_params + failed_case)
            with open(rerun_report, 'r+', encoding='gbk') as f:
                text = f.read()
                text = text.replace('<meta charset="utf-8"/>', '<meta charset="gbk"/>')
                f.seek(0)
                f.write(text)
    print('SmokeTest: End of check, test succeeded!')
except:
    print('SmokeTest: End of check, SmokeTest find some fatal problems! {}'.format(traceback.format_exc()))
